package com.sise.wangzhan;

import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.IPing;
import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.Server;

import java.util.List;
import java.util.Random;

/**
 * @Classname MyRule
 * @Description TODO
 * @Date 2020/3/26 11:11
 * @Created by wangzhan
 */
public class MyRule implements IRule {

    ILoadBalancer Ib;

    public MyRule() {
    }

    public MyRule(ILoadBalancer ib) {
        Ib = ib;
    }

    //编写自己的负载均衡算法
    @Override
    public Server choose(Object o) {

        List<Server> serverList = Ib.getAllServers();

        Random random = new Random();
        int number = random.nextInt(10);

        if (number < 7){
            return findServer(serverList, 8081);
        }
        return findServer(serverList, 8085);
        //return serverList.get(0);
    }

    private Server findServer(List<Server> serverList, int port) {

        for (Server server : serverList){
            if (server.getPort() == port){
                return server;
            }
        }
        System.out.println("NULL port="+port);
        return null;
    }

    @Override
    public void setLoadBalancer(ILoadBalancer iLoadBalancer) {
        Ib = iLoadBalancer;
    }

    @Override
    public ILoadBalancer getLoadBalancer() {
        return this.Ib;
    }


}
